import { Link, useHistory } from 'react-router-dom';
import { useEffect, useRef } from 'react';
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Table,
  Tag,
  Space,
  Modal,
} from 'antd';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { getChannels, getArticles, deleteArticle } from 'store/actions';
import img404 from 'assets/error.png';
import Channel from 'components/Channel';
const { RangePicker } = DatePicker;
// 结构函数的静态属性
const { confirm } = Modal;
const ArticleList = () => {
  const paramsRef = useRef({});
  const history = useHistory();
  const dispatch = useDispatch();
  const { page, pageSize, count, list } = useSelector((state) => state.article);
  useEffect(() => {
    dispatch(getChannels());
    dispatch(getArticles({}));
  }, [dispatch]);

  const onSearch = (values) => {
    const { status, channel_id, date } = values;
    //组装刷选数组
    const params = {};
    if (status !== -1) {
      params.status = status;
    }
    if (channel_id) {
      params.channel_id = channel_id;
    }
    if (date) {
      params.begin_pudate = date[0].format('YYYY-MM-DD HH:mm:ss');
      params.end_pudate = date[1].format('YYYY-MM-DD HH:mm:ss');
    }
    paramsRef.current = params;
    dispatch(getArticles(params));
  };
  const changePage = (page, pageSize) => {
    //分页数据
    const params = {
      // 从 ref 对象中拿筛选数据
      ...paramsRef.current,
      page,
      per_page: pageSize,
    };
    dispatch(getArticles(params));
  };
  const delArticle = (id) => {
    confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '此操作将永久删除该文章，是否继续？',
      onOk: () => {
        try {
          dispatch(deleteArticle(id, paramsRef.current));
        } catch {}
      },
    });
  };
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (cover) => {
        return <img src={cover || img404} width={200} height={150} alt="" />;
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 220,
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (data) => {
        const tagData = articleStatus[data];
        return <Tag color={tagData.color}>{tagData.text}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (data) => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => history.push(`/home/publish/${data.id}`)}
            ></Button>
            <Button
              type="primary"
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => delArticle(data.id)}
            ></Button>
          </Space>
        );
      },
    },
  ];
  //优化文章状态的处理
  const articleStatus = {
    0: { color: 'yellow', text: '草稿' },
    1: { color: '#ccc', text: '待审核' },
    2: { color: 'green', text: '审核通过' },
    3: { color: 'red', text: '审核失败' },
  };

  return (
    <div>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
        style={{ marginBottom: 20 }}
      >
        <Form initialValues={{ status: -1 }} onFinish={onSearch}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="频道" name="channel_id">
            <Channel />
          </Form.Item>
          <Form.Item label="日期" name="date">
            <RangePicker locale={locale}></RangePicker>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card title={`根据筛选条件共查询到 ${count} 条结果：`}>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={list}
          pagination={{
            current: page,
            pageSize,
            total: count,
            showSizeChanger: true,
            onChange: changePage,
            position: ['bottomCenter'],
          }}
        />
      </Card>
    </div>
  );
};
export default ArticleList;
